package test.task.fun.view;

import java.math.BigDecimal;
import java.util.ArrayList;

import test.task.fun.R;
import test.task.fun.model.Goods;
import test.task.fun.model.Goods.Type;
import test.task.fun.service.GoodsStore;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SellActivity extends Activity {

	private GoodsStore goodsStore;
	private Spinner typeSpinner;
	private Type selectedType;
	private ArrayList<Type> types;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_sell);
		Log.e("sellActivity", "create");
		goodsStore = GoodsStore.getInstance(getApplicationContext());

		typeSpinner = (Spinner) findViewById(R.id.act_sell_type);
		typeSpinner.setSelection(0);

		types = new ArrayList<Goods.Type>();
		types.add(Goods.Type.AVAILABLE);
		types.add(Goods.Type.UN_AVAILABLE);
		selectedType = types.get(0);

		ArrayAdapter<Goods.Type> adapter = new ArrayAdapter<Goods.Type>(this, android.R.layout.simple_spinner_item,
				types);

		typeSpinner.setAdapter(adapter);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				selectedType = types.get(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}

		});

	}

	public void sell(View view) {
		Goods goods = getGoods();
		if (checkGoods(goods)) {
			goodsStore.addGoods(goods);
			Toast.makeText(this, R.string.sell_success, Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, R.string.error_field_empty, Toast.LENGTH_SHORT).show();
		}

	}

	private boolean checkGoods(Goods goods) {
		if (isEmptyString(goods.getName())) {
			return false;
		}
		if (goods.getPrice() == null) {
			return false;
		}

		return true;
	}

	private boolean isEmptyString(String name) {
		return name == null || "".equals(name);
	}

	private Goods getGoods() {
		Goods goods = new Goods();

		TextView name = (TextView) findViewById(R.id.act_sell_name);
		goods.setName(name.getText().toString());

		goods.setType(selectedType);

		TextView price = (TextView) findViewById(R.id.act_sell_price);
		if (!isEmptyString(price.getText().toString())) {
			goods.setPrice(new BigDecimal(price.getText().toString()));
		}
		return goods;
	}

}
